package com.reservationserver.service.impl.user;

import com.alibaba.fastjson.JSONObject;
import com.reservationpojo.entity.Badminton;
import com.reservationpojo.utils.Qrcode;
import com.reservationserver.mapper.user.UserBadmintonMapper;
import com.reservationserver.service.user.UserBadmintonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserBadmintonServiceimpl implements UserBadmintonService {

    private final UserBadmintonMapper badmintonMapper;

    private final RedisTemplate redisTemplate;

    /**
     * 预约操作，生成二维码记录到redis中过期时间为两天，数据库记录预约信息
     * @param badminton 预约信息
     */
    @Override
    public void reservePosition(Badminton badminton) throws IOException {
        String redisKey="badminton"+badminton.getReservedByid()+badminton.getPosition()+badminton.getReservationStartTime().toString();
        log.info("dasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasd{}",badminton);
        if(!Objects.equals(redisTemplate.opsForValue().get(redisKey),null)){
            return;
        }

        badminton.setStatus("未到场");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTime = LocalDateTime.now().format(formatter);
        badminton.setCreateTime(formattedTime);
        log.info("生成二维码的base64格式数据");
        String message = JSONObject.toJSONString(badminton);
        String image=Qrcode.creatRrCode(message);
        redisTemplate.opsForValue().set("badminton"+formattedTime+badminton.getReservedByid(),image,2, TimeUnit.DAYS);
        badmintonMapper.reservePosition(badminton);
    }
    /**
     * 查询预约
     * @param uid 学号
     * @return 预约信息
     */
    @Override
    public List<Badminton> checkReservation(String uid,Integer page) {
        log.info("查询预约...");
        page=(page-1)*10;
        return badmintonMapper.checkReservation(uid,page);
    }

    /**
     * 取消预约，同时删除redis中对用的二维码
     * @param badminton 全部的预约信息
     */
    @Override
    public void deleteReservation(Badminton badminton) {
        log.info("用户取消预约");
        badminton.setStatus("已取消");
        badmintonMapper.deleteReservation(badminton);
        String formattedTime = badminton.getCreateTime();
        redisTemplate.delete("badminton"+formattedTime+badminton.getReservedByid());
    }
}
